//1.生成接口文档的内容
const swaggerJSDoc = require("swagger-jsdoc");
const path = require("path");
const { koaSwagger } = require("koa2-swagger-ui");
const { SERVER_HOST, SERVER_PORT } = require("../config/server");

const SWAGGER_UI = "/swagger";
const SWAGGER_JSON_ADDRESS = "/swagger/swagger.json";

const swaggerDefinition = {
  info: {
    title: "刘乙江的知识库",
    version: "1.0.0",
    description: "API",
  },
  host: `${SERVER_HOST}:${SERVER_PORT}`,
  basePath: "/", // Base path (optional)
  securityDefinitions: {
    // 定义安全方案
    token: {
      type: "apiKey",
      name: "token",
      in: "header", // 请求头中传递
    },
  },
};
const options = {
  swaggerDefinition,
  apis: [path.join(__dirname, "../router/*.js")], //配置路由router文件的位置
};
const swaggerSpec = swaggerJSDoc(options);

//2.new一个路由
const koaRouter = require("@koa/router");
const swaggerRouter = new koaRouter();
//3.生成注册器
function registerSwagger(app) {
  // swagger配置
  app.use(swaggerRouter.routes(), swaggerRouter.allowedMethods());
  app.use(
    koaSwagger({
      routePrefix: SWAGGER_UI, //界面的访问地址
      swaggerOptions: {
        url: SWAGGER_JSON_ADDRESS, //swagger.json文件的访问地址
      },
    })
  );
  swaggerRouter.get(SWAGGER_JSON_ADDRESS, async function (ctx) {
    //这个路由必须有,因为上边的swaggerOptions.url访问的就是这个路由返回的json
    ctx.set("Content-Type", "application/json");
    ctx.body = swaggerSpec;
  });
}

module.exports = registerSwagger;
